package com.bwie.controller;

import com.alibaba.fastjson.JSON;
import com.bwie.es.EsProduct;
import com.bwie.pojo.Detail;
import com.bwie.pojo.Image;
import com.bwie.pojo.Linkage;
import com.bwie.pojo.Product;

import com.bwie.service.DetailService;
import com.bwie.service.ImageService;
import com.bwie.service.LinkageService;
import com.bwie.service.ProductService;

import com.bwie.unit.FreemarkerUtil;
import com.bwie.unit.MessageVo;
import com.bwie.unit.R;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.rabbitmq.client.Channel;
import freemarker.template.TemplateException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

   @Autowired
   private StringRedisTemplate stringRedisTemplate;

   @Autowired
   private RabbitTemplate rabbitTemplate;

    @Autowired
    private LinkageService linkageService;

    @Autowired
    private ImageService imageService;

    @Autowired
    private DetailService detailService;

    @PostMapping("foundEs")
    public R foundEs(){
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(EsProduct.class);
        boolean exists = indexOperations.exists();
        if (exists){
            indexOperations.delete();
        }
        indexOperations.create();
        Document mapping = indexOperations.createMapping();
        indexOperations.putMapping(mapping);
        return R.OK();
    }


    @PostMapping("EsPageList")
    public R EsPageList(@RequestBody Product product, @RequestHeader(name = "token") String token){
          //模糊查询
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (!StringUtils.isEmpty(product.getProductName())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("productName",product.getProductName()));
        }

        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("productName").preTags("<font color = 'red'>"
        ).postTags("</font>");

        //分页
        int pageNum = 0;
        if (product.getPageNum()>0){
            pageNum = product.getPageNum()-1;
        }
        PageRequest of = PageRequest.of(pageNum, product.getPageSize());




        //组合查询
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withPageable(of)
                .withHighlightBuilder(highlightBuilder)
                .withQuery(boolQueryBuilder);

        SearchHits<EsProduct> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), EsProduct.class);
        long total= search.getTotalHits();

        ArrayList<EsProduct> list = new ArrayList<>();
        for (SearchHit<EsProduct> esProductSearchHit : search) {
            List<String> goodsName = esProductSearchHit.getHighlightField("productName");
            EsProduct content = esProductSearchHit.getContent();
            if (goodsName!=null && goodsName.size()>0){
                String s = goodsName.get(0);
                content.setProductName(s);
            }
            list.add(content);
        }
        HashMap<String  , Object> map = new HashMap<>();
        map.put("list",list);
        map.put("total",total);
        map.put("pageNum",pageNum);
        map.put("pageSize",product.getPageSize());
        return R.OK(map);
    }



    //级联器
    @PostMapping("linkageList")
    public R linkageList() {
       List<Linkage> linkageList = linkageService.linkageList();
       return R.OK(linkageList);
    }
    //添加
    @PostMapping("addProduct")
    public R addProduct(@RequestBody Product product,@RequestHeader(name = "token") String token){
        Claims body = Jwts.parser().setSigningKey("bwie".getBytes()).parseClaimsJws(token).getBody();
        Integer uid = body.get("uid", Integer.class);
        product.setUserId(uid);
        List<Image> imageList = product.getImageList();
        productService.save(product);
        for (Image image : imageList) {
            image.setProductId(product.getId());
            imageService.save(image);
        }
        MessageVo messageVo = new MessageVo();
        String msgId = UUID.randomUUID().toString();
        messageVo.setMsgId(msgId);
        messageVo.setMsgBody(String.valueOf(product));
        stringRedisTemplate.opsForValue().set(msgId, String.valueOf(product),15, TimeUnit.MINUTES);
        rabbitTemplate.convertAndSend("directExchange","", JSON.toJSONString(messageVo));
        return R.OK();
    }

    @RabbitListener(queues = "addQueue")
    public void queue(String msg, Message message, Channel channel) throws IOException {
        MessageVo messageVo = JSON.parseObject(msg, MessageVo.class);
        String msgId = messageVo.getMsgId();
        if (!stringRedisTemplate.hasKey(msgId)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
            return;
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        return;
    }

    @PostMapping("detailList")
    public R detailList(){
        List<Detail> list = detailService.list();
        return R.OK(list);
    }


}
